<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="login-form-left">
        <div class="main-wrap-left-text">
          <img
            class="main-wrap-right-logo"
            src="@/assets/common/main-logo.png"
            width="190px"
          />
          <h1 class="main-wrap-left-title">人才招聘后台管理</h1>
          <p class="main-wrap-left-subtitle">Technology backend management</p>
        </div>
        <img class="main-wrap-left-img" src="@/assets/common/img-main.png" />
      </div>
      <div class="login-form-right">
        <div class="title-container">
          <h3 class="title">{{ $t("login.title") }}</h3>
          <p class="main-wrap-right-subtitle">{{ $t("login.futitle") }}</p>
        </div>
        <template>
          <el-tabs
            v-model="loginType"
            type="border-card"
            @tab-click="handleClick"
          >
            <el-tab-pane label="手机号登入" name="1">
              <el-form-item prop="phone">
                <span class="svg-container">
                  <svg-icon icon-class="user" />
                </span>
                <el-input
                  ref="phone"
                  v-model="loginForm.phone"
                  :placeholder="$t('login.name')"
                  name="phone"
                  type="text"
                  tabindex="1"
                  auto-complete="on"
                />
              </el-form-item>
              <el-row>
                <el-col :span="14">
                  <el-form-item style="display: flex">
                    <span class="svg-container">
                      <svg-icon icon-class="password" />
                    </span>
                    <el-input
                      v-model="loginForm.code"
                      placeholder="请输入验证码"
                      style="width: 80%"
                      @keyup.native.enter="handleLogin"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-button
                    type="primary"
                    style="
                      margin-top: 0;
                      margin-left: 10%;
                      padding: 18px 0px;
                      width: 120px;
                    "
                    @click="initCaptcha"
                    >{{ codeText }}</el-button
                  >
                </el-col>
              </el-row>
              <el-button
                :loading="loading"
                type="primary"
                style="width: 100%; margin-bottom: 30px"
                @click.native.prevent="handleLogin"
                >{{ $t("login.login") }}</el-button
              >
            </el-tab-pane>
            <el-tab-pane label="仑传扫码登入" name="2">
              <div v-loading="loading" class="login-code-box">
                <img :src="qrCode" />
              </div>
              <div class="qrCde_refresh">
                <el-button
                  type="text"
                  icon="el-icon-refresh"
                  style="margin: 0px; padding: 0px"
                  @click="refreshBtn"
                  >点击刷新二维码</el-button
                >
              </div>
            </el-tab-pane>
            <el-tab-pane label="企业App下载" name="3">
              <div class="qrcode-container">
                <img
                  src="@/assets/common/仑传二维码下载.jpg"
                  alt=""
                  class="qrcode-image"
                />
              </div>
            </el-tab-pane>
          </el-tabs>
        </template>
        <p class="main-wrap-right-bottom">{{ $t("login.thirdpartyTips") }}</p>
      </div>
    </el-form>
  </div>
</template>

<script>
import { validMobile } from "@/utils/validate";
import { mapActions } from "vuex";
import { AddQrCode, CaptchaGraphicCode } from "@/api/user";
import QRCode from "qrcode";
import { setTimeout } from "core-js";
import user from "@/store/modules/user";
export default {
  name: "Login",
  data() {
    const validateMobile = (rule, value, callback) => {
      validMobile(value)
        ? callback()
        : callback(new Error(this.$t("prompt.phoneFormat")));
    };
    return {
      id: undefined,
      sms_code: "",
      loginType: "1",
      qrCode: "",
      intervalId: null,
      count: 0,
      maxCount: 30,
      codeId: 0,
      countCode: 60,
      codeText: "获取验证码",
      isCode: false,
      loginForm: {
        phone: "",
        code: "",
        bid: 1,
      },
      loginRules: {
        phone: [
          {
            required: true,
            trigger: "blur",
            message: this.$t("prompt.phoneEmpty"),
          },
          {
            validator: validateMobile,
            trigger: "blur",
          },
        ],
      },
      loading: false,
      redirect: undefined,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.initAlicom4 = window.initAlicom4;
  },
  methods: {
    ...mapActions(["user/login"]), // 引入方法
    ...mapActions(["user/loginQ"]),
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleClick(event) {
      if (event.name === "2") {
        this.stopTask();
        this.qrCodeAdd();
      } else {
        this.stopTask();
      }
    },
    // 刷新二维码
    refreshBtn() {
      this.stopTask();
      this.qrCodeAdd();
    },
    initCaptcha() {
      if (this.isCode) {
        return;
      }
      if (this.loginForm.phone === "") {
        this.$message.error("手机号码不能为空！");
        return;
      }
      this.initAlicom4(
        {
          captchaId: "7ac14c9578f231f8dfa8bc7670da98e5",
          product: "bind",
        },
        (captchaObj) => {
          // 处理回调逻辑
          captchaObj.showCaptcha();
          captchaObj.onSuccess(() => {
            var result = captchaObj.getValidate();
            this.codeBtn(result);
          });
          captchaObj.onNextReady(function () {
            this.dialogVisible = true;
          });
          captchaObj.onBoxShow(function () {
            console.log("boxShow");
          });
          captchaObj.onError(function (e) {
            console.log(e);
          });
        }
      );
    },
    // 获取验证码
    async codeBtn(row) {
      const one = {
        phone: this.loginForm.phone,
        lot_number: row.lot_number,
        captcha_output: row.captcha_output,
        pass_token: row.pass_token,
        gen_time: row.gen_time,
        captcha_id: row.captcha_id,
      };
      const res = await CaptchaGraphicCode(one);
      if (res.code === 0) {
        this.$message.success("验证码已发送！");
        this.startTaskCode();
      }
    },
    // 生成二维码记录
    async qrCodeAdd() {
      try {
        this.loading = true;
        const { id, sms_code } = await AddQrCode();
        this.id = id;
        this.sms_code = sms_code;
        const cur =
          "https://bm.nbblmc.cn/hr_login.html?id=" +
          this.id +
          "&code=" +
          this.sms_code;
        this.generateQRCode(cur);
      } catch (error) {
        this.loading = false;
        this.$message.error(error);
      }
    },
    // 生成二维码
    generateQRCode(e) {
      QRCode.toDataURL(e)
        .then((url) => {
          this.qrCode = url;
          this.loading = false;
          setTimeout(() => {
            this.startTask();
          }, 3000);
        })
        .catch((err) => {
          console.error(err);
          this.loading = false;
        });
    },
    // 调用定时登入
    async LoginQD() {
      try {
        const one = {
          id: this.id,
        };
        // 校验成功后，调用action
        await this["user/loginQ"](one); // 使用asyns await来强制限制异步api完成后执行
        // 转跳到主页
        this.$router.push("/");
      } catch (error) {
        // 如果失败，catch跳出方法
        console.log(error);
      } finally {
        // 不论执行try还是catch，都将执行finally中的代码
        this.loading = false;
      }
    },
    startTaskCode() {
      this.isCode = true;
      this.codeId = setInterval((res) => {
        if (this.countCode > 0) {
          this.countCode--;
          if (parseFloat(user.state.userId) > 0) {
            this.stopTaskCode();
          } else {
            this.codeText = "倒计时 " + this.countCode + "s";
          }
        } else {
          this.stopTaskCode();
        }
      }, 1000);
    },
    stopTaskCode() {
      if (this.codeId !== 0) {
        clearInterval(this.codeId);
        this.codeId = 0;
        this.isCode = false;
        this.codeText = "获取验证码";
        this.countCode = 60;
      }
    },
    startTask() {
      this.intervalId = setInterval((res) => {
        if (this.count < this.maxCount) {
          this.count++;
          if (parseFloat(user.state.userId) > 0) {
            this.stopTask();
          } else {
            this.LoginQD();
          }
        } else {
          this.stopTask();
        }
      }, 3000);
    },
    stopTask() {
      if (this.intervalId) {
        clearInterval(this.intervalId);
        this.count = 0;
      }
    },
    handleLogin() {
      // 开启手动校验表单
      this.$refs.loginForm.validate(async (isOk) => {
        if (isOk) {
          try {
            this.loading = true; // 开启转圈
            // 校验成功后，调用action
            await this["user/login"](this.loginForm); // 使用asyns await来强制限制异步api完成后执行
            // 转跳到主页
            this.$router.push("/");
          } catch (error) {
            // 如果失败，catch跳出方法
            console.log(error);
          } finally {
            // 不论执行try还是catch，都将执行finally中的代码
            this.loading = false;
          }
        }
      });
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #edeff5;
$light_gray: #555;
$cursor: #555;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: #edeff5;
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #333;

.login-container {
  background-position: center;
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  background-image: url("~@/assets/common/bg-admin2.png");
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;

  .login-form {
    position: relative;
    max-width: 100%;
    width: 980px;
    height: 590px;
    margin: auto auto;
    overflow: hidden;
    display: flex;
    background-color: #fff;
    align-items: center;
    .login-form-left {
      background-image: linear-gradient(157deg, #0c1741 0%, #071232 96%);
      width: 540px;
      height: 100%;
      position: relative;
      .main-wrap-left-text {
        color: #fff;
        padding: 30px 30px;
        text-align: left;
        .main-wrap-right-logo {
          margin-bottom: 10px;
        }
        .main-wrap-left-title {
          font-size: 36px;
          font-weight: 600;
          color: #fff;
          line-height: 48px;
          margin-top: 0px;
          margin-bottom: 0px;
          letter-spacing: 4px;
        }
        .main-wrap-left-subtitle {
          font-size: 12px;
          color: #797f91;
          letter-spacing: 4px;
          margin: 5px 0 20px;
        }
      }
      .main-wrap-left-img {
        width: 480px;
        height: 400px;
        position: absolute;
        bottom: 50px;
        right: 0;
      }
    }
    .login-form-right {
      position: relative;
      height: 100%;
      width: 460px;
      padding: 60px 40px;
      text-align: left;
      .main-wrap-right-subtitle {
        margin: 12px 0 40px;
        font-size: 13px;
      }
      .title-container {
        position: relative;

        .title {
          font-size: 28px;
          color: $light_gray;
          margin: 0px;
          font-weight: bold;
        }
      }
      .el-button {
        margin-top: 30px;
        padding: 15px 20px;
      }
      .main-wrap-right-bottom {
        position: absolute;
        bottom: 20px;
        font-size: 12px;
        text-align: center;
        color: #8d8d8d;
        left: 50%;
        transform: translateX(-50%);
        width: 100%;
      }
    }
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
.login-code-box {
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    width: 80%;
  }
}
.qrCde_refresh {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #409eff;
}

.qrcode-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
}

.qrcode-image {
  max-width:250px; // 可以根据需要调整大小
  height: auto;
}
</style>
